package com.tanhua.server.service;


import com.alibaba.fastjson.JSON;
import com.tanhua.commons.templates.HuanXinTemplate;
import com.tanhua.domain.db.Question;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.RecommendUser;
import com.tanhua.domain.vo.PageResult;
import com.tanhua.domain.vo.RecommendUserQueryParam;
import com.tanhua.domain.vo.RecommendUserVo;
import com.tanhua.domain.vo.UserInfoVo;
import com.tanhua.dubbo.api.QuestionApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.mongo.RecommendUserApi;
import com.tanhua.server.interceptor.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 交友--消费者模块
 */
@Service
@Slf4j
public class RecommendUserService {

    //远程注入 RecommendUserApi
    @Reference
    private RecommendUserApi recommendUserApi;

    //远程注入 UserInfoApi
    @Reference
    private UserInfoApi userInfoApi;

    @Reference
    private QuestionApi questionApi;

    @Autowired
    private HuanXinTemplate huanXinTemplate;


    /**
     * 今日佳人
     */
    public RecommendUserVo todayBest() {
        //1.获取登录用户的id
        Long loginUserId = UserHolder.getUserId();
        //2.通过登录用户调用mongodb查询，推荐这个用户缘分值最高的用户id
        RecommendUser recommendUser = recommendUserApi.todayBest(loginUserId);

        //3.判断是否有这个推荐用户（佳人）
        if (null == recommendUser) {
            //4.如果没有--设置一个默认用户
            recommendUser = new RecommendUser();
            //设置推荐佳人id
            recommendUser.setUserId(RandomUtils.nextLong(1, 99));
            //设置推荐佳人缘分值
            recommendUser.setScore(RandomUtils.nextDouble(60, 80));

        }
        //5.查询这个佳人的详细信息
        UserInfo userInfo = userInfoApi.findById(recommendUser.getUserId());

        //6.构建vo
        RecommendUserVo vo = new RecommendUserVo();
        //7.复制属性
        BeanUtils.copyProperties(userInfo, vo);
        //
        vo.setTags(StringUtils.split(userInfo.getTags(), ","));

        vo.setFateValue(recommendUser.getScore().longValue());

        log.info("今日佳人是" + vo);
        //8.返回
        return vo;

    }

    /**
     * 推荐朋友
     *
     * @param queryParam
     * @return
     */
    public PageResult<RecommendUserQueryParam> recommendList(RecommendUserQueryParam queryParam) {
        //获取登录用户id
        Long loginUserId = UserHolder.getUserId();
        //查询推荐朋友
        PageResult result = recommendUserApi.recommendList(queryParam.getPage(), queryParam.getPagesize(), loginUserId);

        //取出分页结果集中的数据
        List<RecommendUser> records = (List<RecommendUser>) result.getItems();

        //如果分页结果集没有查询到数据 需要设置默认数据
        if (CollectionUtils.isEmpty(records)) {

            records = defaultRecommend();
            result.setPages(1L);
            result.setCounts(10L);

        }
        //PageResult中items需要集合数据，这里构建一个voList集合用来和RecommendUser相互转换数据后给前端返回
        List<RecommendUserVo> vos = new ArrayList<>();
        //取出分页结果集中的数据进行转换
        for (RecommendUser record : records) {
            //vos中的每一个vo在这里构建并添加数据
            RecommendUserVo vo = new RecommendUserVo();

            //推荐用户的详情
            UserInfo userInfo = userInfoApi.findById(record.getUserId());
            //复制属性
            BeanUtils.copyProperties(userInfo, vo);
            //缘分值
            vo.setFateValue(record.getScore().longValue());
            // tags处理用逗号分开
            vo.setTags(StringUtils.split(userInfo.getTags(), ","));

            //vos把每一个装有数据的vo收集起来
            vos.add(vo);


        }
        //设置分页结果集中的tems
        result.setItems(vos);

        //返回
        return result;
    }

    /**
     * 构建推荐朋友的默认数据
     *
     * @return
     */
    private List<RecommendUser> defaultRecommend() {
        List<RecommendUser> list = new ArrayList<>();

        for (long i = 1; i <= 10; i++) {
            RecommendUser recommendUsers = new RecommendUser();
            recommendUsers.setUserId(i);
            //设置缘分值
            recommendUsers.setScore(RandomUtils.nextDouble(60, 80));
            list.add(recommendUsers);


        }
        return list;
    }

    /**
     * 佳人信息
     *
     * @param userId
     * @return
     */
    public RecommendUserVo getPersonalInfo(Long userId) {
        //查询登录用户与佳人的缘分值
        Double score = recommendUserApi.findByid(UserHolder.getUserId(), userId);
        //查询佳人的信息
        UserInfo UserInfo = userInfoApi.findById(userId);
        //构建vo返回
        RecommendUserVo vo = new RecommendUserVo();
        //复制属性
        BeanUtils.copyProperties(UserInfo, vo);
        //tags处理
        vo.setTags(StringUtils.split(UserInfo.getTags(), ","));
        //缘分值
        vo.setFateValue(score.longValue());
        return vo;
    }


    /**
     * 查看陌生人问题
     *
     * @param userId
     * @return
     */
    public String strangerQuestions(Long userId) {
        //查询问题表，获取陌生人问题
        Question question = questionApi.selectById(userId);

        //如果问题为空，设置一个默认值
        if (question == null) {
            return "奇便偶不变";
        }
        return question.getTxt();
    }

    /**
     * 回复陌生人问题
     *
     * @param paramMap
     */
    public void replyStrangerQuestions(Map<String, Object> paramMap) {
        //佳人的id
        Integer userId = (Integer) paramMap.get("userId");

        //1.获取发送人id
        Long loginUserId = UserHolder.getUserId();
        //2.发送者昵称
        UserInfo userInfo = userInfoApi.findById(loginUserId);
        String nickname = userInfo.getNickname();
        //3.回复的内容
        String reply = (String) paramMap.get("reply");
        //佳人的问题
        Question question = questionApi.selectById(userId.longValue());

        String strangerQuestion = null;

        if(question==null){
            strangerQuestion="奇变偶不变";
        }else {
            strangerQuestion = question.getTxt();
        }
        //5. 构建环信消息内容 构建四个参数，发送人id，发送者昵称，问题，答案
        Map<String, Object> map = new HashMap<>();
        map.put("userId",loginUserId); //发送者id
        map.put("nickname",nickname); //发送者昵称
        map.put("strangerQuestion",strangerQuestion); //问题
        map.put("reply",reply); //答案


        //6. 调用环信发送消息
        huanXinTemplate.sendMsg(userId.toString(), JSON.toJSONString(map));
    }
}
